package com.fhz.kotlintest.databinding.fragment

import android.util.Log
import androidx.recyclerview.widget.StaggeredGridLayoutManager
import com.fhz.kotlintest.Data
import com.fhz.kotlintest.R
import com.fhz.kotlintest.RVAdapter
import com.fhz.kotlintest.databinding.FoodFragmentBinding
import com.fhz.kotlintest.databinding.adapter.RVDataBindingAdapter
import com.fhz.kotlintest.databinding.base.BaseVMFragment

class FoodFragment : BaseVMFragment<FoodFragmentBinding,FoodViewModel>() {

    private  val TAG = "FoodFragment"

    override fun getVMClass(): Class<FoodViewModel> = FoodViewModel::class.java

    override fun getLayoutId(): Int = R.layout.food_fragment

    //数据更新
    override fun observableData() {

        viewModel.loadState.observe(this,{
            Log.i(TAG, "state: $it")
        })
        
        viewModel.contentList.observe(this,{
            Log.i(TAG, "内容: ${it[0].title}")
            list.clear()
            list.addAll(it)
            rvAdapter.notifyDataSetChanged()
        })
    }

    //开始数据的读取
    override fun startLoadData() {
        viewModel.loadData()
    }

    //数据源
    private val list:MutableList<Data> = mutableListOf()
    //适配器
//    private lateinit var rvAdapter:RVAdapter
    private lateinit var rvAdapter:RVDataBindingAdapter

    override fun initEvent() {
        rvAdapter = RVDataBindingAdapter(R.layout.rv_databinding_layout,list)
        binding.foodRecycleView.adapter = rvAdapter
        binding.foodRecycleView.layoutManager = StaggeredGridLayoutManager(2,StaggeredGridLayoutManager.VERTICAL)

        binding.smart.setOnLoadMoreListener {
            viewModel.loadMoreData()
            it.finishLoadMore()
        }
    }
}